﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public enum VirusesState {
    Free,
    Combin
}

[RequireComponent(typeof(Cell))]
public class Viruses : MonoBehaviour {
    public GameObject InfectedCell;//预制体
    private GameObject m_Target;

    private VirusesState m_State;

    private Cell m_Cell;

    public GameObject destroyEffect;

    private void Awake() {
        m_State = VirusesState.Free;
        m_Cell = GetComponent<Cell>();
    }

    private void OnDestroy() {
        //if(destroyEffect != null) {
       //     GameObject obj = Instantiate(destroyEffect, this.transform.position, Quaternion.identity);
       //     Destroy(obj, 2f);
        //}
            
    }

	private void Update () {
        //如果是没有结合的病毒
        if (m_State == VirusesState.Free) {
            // GameObject target = Distinguish();
            GameObject target = m_Cell.UpdateTarget(Combin);
            if (target != null) {
                m_Cell.FollowTarget(target);
            } else {
                m_Cell.Wander();
            }
        }
	}

    // //识别目标
    // public GameObject Distinguish() {
    //     RaycastHit2D[] rh = Physics2D.CircleCastAll(transform.position, m_Cell.DetectRange, transform.up, 0);
    //     float Dmin = 9999;
    //     if (rh != null) {
    //         foreach (RaycastHit2D hit in rh) {
    //             if (hit.collider.tag == m_Cell.TargetTag) {
    //                 Vector3 dir = hit.collider.gameObject.transform.position - transform.position;

    //                 if (Dmin >= dir.magnitude) {
    //                     Dmin = dir.magnitude;

    //                     m_Target = hit.collider.gameObject;
    //                     if (dir.magnitude < m_Cell.AttackRange) {
    //                         Combin(m_Target);
    //                     }
    //                 }
    //             }
    //         }
    //     }
    //     return m_Target;
    // }

    //寄生结合
    public void Combin(GameObject target) {
        Instantiate(InfectedCell, target.transform.position, Quaternion.identity);
        
        Destroy(target);
        this.gameObject.SetActive(false);
        Destroy(this.gameObject, 0.1f);
    }
}
